package com.hangwei.paperless.view.repair;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hangwei.paperless.BottomPopType;
import com.hangwei.paperless.MainRepairActivity;
import com.hangwei.paperless.R;
import com.hangwei.paperless.adapter.MainRepairAdapter;
import com.hangwei.paperless.model.bean.BasicInfoBean;
import com.hangwei.paperless.model.bean.CardToSeal;
import com.hangwei.paperless.model.bean.DRSInfo;
import com.hangwei.paperless.model.bean.RecordListBean;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.utils.Constants;
import com.hangwei.paperless.utils.JsonPostUtil;
import com.hangwei.paperless.utils.NFCCallBack;
import com.hangwei.paperless.view.BaseView;
import com.twelve.all.net.CallBack;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.hangwei.paperless.MainRepairActivity.mStepId;

/**
 * Created by 张龙臣 on 2020/11/20.
 */

public abstract class BaseMainRepairView extends BaseView<MainRepairActivity, List<RecordListBean>> {

    private LinearLayout mLlOpen;

    public BaseMainRepairView(MainRepairActivity activity) {
        super(activity);
    }

    private RecyclerView mRecyclerView;
    private String currentTab = "";
    private MainRepairAdapter mAdapter;
    private boolean mDrsHasSaved = false;

    @Override
    protected View initView() {
        currentTab = getCurrentPage();
        View inflate = LayoutInflater.from(mActivity).inflate(R.layout.page_base_main_repair, null);
        TextView tvTitle = (TextView) inflate.findViewById(R.id.tvTitle);
        tvTitle.setText(getTitle());
        mRecyclerView = inflate.findViewById(R.id.recyclerView);
        RelativeLayout rlOpen = inflate.findViewById(R.id.rlOpen);
        rlOpen.setOnClickListener(this);
        mLlOpen = inflate.findViewById(R.id.llOpen);
        final String userId0 = SPUtil.getString(SPKey.Account.USER_ID);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter = new MainRepairAdapter(null, 0) {
            @Override
            protected void onNaCurrent(String id) {
                mActivity.showBottomPopupWindow(BottomPopType.NA, id);
            }

            @Override
            protected void seal(final RecordListBean item, final int stampRole, final String resultVal) {
                //判断是否是当前执行行
                if (!item.id.equals(mStepId)) {
                    return;
                }
                //先判断有无DRS信息
                if (item.isDrs && 1 == stampRole && !mDrsHasSaved) {
                    ToastUtil.showCenterToast("请先保存DRS信息！");
                    return;
                }
                //选印章
//                if (App.stamps != null && App.stamps.size() > 0) {
//                    //有印章
//                    MainBottomPopupWindow mainBottomPopupWindow = mActivity.showBottomPopupWindow(BottomPopType.Seal);
//                    mainBottomPopupWindow.setOnSealListener(new MainBottomPopupWindow.OnSealListener() {
//                        @Override
//                        public void onSeal(String stampId) {
//                            final LoadingDialog loadingDialog = new LoadingDialog(mActivity);
//                            loadingDialog.show();
//
//                            StaticPresenter.stampRoutingSheetStep(userId, mActivity.getBillId(), item.id, stampRole, userId, stampId, resultVal, new CallBack<Object>() {
//                                @Override
//                                public void onCompleted(Object o) {
//                                    loadingDialog.dismiss();
//                                    mActivity.closeBottomPop();
//                                    initData();
//                                }
//
//                                @Override
//                                public void onError() {
//                                    loadingDialog.dismiss();
//                                }
//                            });
//                        }
//                    });
//                } else {
//                    ToastUtil.showCenterToast("无印章");
//                }

                mActivity.sealByCard(item.id, new NFCCallBack() {
                    @Override
                    public void onCallBack(List<CardToSeal.StampBean> stampIds, String userId) {
                        if (stampIds == null || stampIds.size() == 0) {
                            ToastUtil.showCenterToast("无印章！");
                        } else {
                            final LoadingDialog loadingDialog = new LoadingDialog(mActivity);
                            loadingDialog.show();
                            StaticPresenter.stampRoutingSheetStep(userId0, mActivity.getBillId(), item.id, stampRole, userId, stampIds.get(0).stampId, resultVal, new CallBack<Object>() {
                                @Override
                                public void onCompleted(Object o) {
                                    loadingDialog.dismiss();
                                    mActivity.closeBottomPop();
                                    initData();
                                }

                                @Override
                                public void onError() {
                                    loadingDialog.dismiss();
                                }
                            });
                        }
                    }
                });
            }

            @Override
            protected void showBigPic(ArrayList<String> data, int position) {
                mActivity.showBigPic(data, position);
            }

            @Override
            protected void onSaveDRS(List<DRSInfo.DrsBean> drsList) {
                final LoadingDialog loadingDialog = new LoadingDialog(mActivity);
                loadingDialog.show();
                String jsonData = JsonPostUtil.buildRSSaveJson(mUserId, mActivity.getBillId(), mStepId, drsList);
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonData);
                StaticPresenter.saveStepDrs(requestBody, new CallBack<Object>() {
                    @Override
                    public void onCompleted(Object o) {
                        mDrsHasSaved = true;
                        ToastUtil.showCenterToast("保存成功");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onError() {
                        loadingDialog.dismiss();
                    }
                });
            }
        };
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                List<RecordListBean> data = mAdapter.getData();
                if (data.size() > 0) {
                    String id = data.get(data.size() - 1).id;
                    final long currentTimeMillis = System.currentTimeMillis();
                    StaticPresenter.getExRoutingSheetStepByPage(mUserId, mActivity.getBillId(), "down", id, Constants.PAGE_SIZE, new CallBack<List<RecordListBean>>() {
                        @Override
                        public void onCompleted(List<RecordListBean> listBeans) {
                            long deTime = System.currentTimeMillis() - currentTimeMillis;
//                            if (deTime < 500)
//                                SystemClock.sleep(500 - deTime);
                            mAdapter.addData(listBeans);
                            if (listBeans.size() >= Constants.PAGE_SIZE) {
                                mAdapter.loadMoreComplete();
                            } else {
                                mAdapter.loadMoreEnd(false);
                            }
                        }

                        @Override
                        public void onError() {
//                            mAdapter.setEnableLoadMore(true);
                        }
                    });
                }
            }
        }, mRecyclerView);
        mRecyclerView.setAdapter(mAdapter);
        initData();
        return inflate;
    }

    protected abstract String getTitle();

    protected abstract String getCurrentPage();

    @Override
    public void bindData(List<RecordListBean> recordList) {
        mAdapter.setNewData(recordList);
        if (recordList != null && recordList.size() > 0)
            checkCanOpen(recordList.get(0).id);
        else mLlOpen.setVisibility(View.GONE);
    }


    private void checkCanOpen(String id) {
        StaticPresenter.getExRoutingSheetStepByPage(mUserId, mActivity.getBillId(), "up", id, Constants.PAGE_SIZE, new CallBack<List<RecordListBean>>() {
            @Override
            public void onCompleted(List<RecordListBean> listBeans) {
                if (listBeans == null || listBeans.size() == 0)
                    mLlOpen.setVisibility(View.GONE);
                else mLlOpen.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError() {
                mLlOpen.setVisibility(View.GONE);
            }
        });
    }

    private void initData() {
        mDrsHasSaved = false;
        final LoadingDialog dialog = new LoadingDialog(mActivity);
        dialog.show();
        final String userId = SPUtil.getString(SPKey.Account.USER_ID);
        StaticPresenter.getExRoutingSheetSteps(userId, mActivity.getBillId(), new CallBack<List<RecordListBean>>() {
            @Override
            public void onCompleted(final List<RecordListBean> recordList) {

                StaticPresenter.getRoutingSheetInfo(userId, mActivity.getBillId(), new CallBack<BasicInfoBean>() {
                    @Override
                    public void onCompleted(BasicInfoBean basicInfoBean) {
                        dialog.dismiss();
                        if (basicInfoBean != null) {
                            MainRepairActivity.pwoNo = basicInfoBean.pwoNo;
                        }
                        String[] split1 = basicInfoBean.curExStep.split("-");
                        String anObject = split1[0];
                        String currentPage = getCurrentPage();
                        mActivity.setStep(basicInfoBean.curExStep);
                        if (!currentPage.equals(anObject)) {
                            LogUtil.d("-------------");
                            mActivity.fixedAndLoad(basicInfoBean.curExStep);
                            return;
                        }
                        //对比确认当前执行行
                        for (RecordListBean recordListBean : recordList) {
                            if (recordListBean.id != null && recordListBean.id.equals(basicInfoBean.curExId)) {
                                recordListBean.isCurrent = true;
                                recordListBean.isDrsOpen = recordListBean.isDrs || recordListBean.isPicture;
                                mStepId = recordListBean.id;
                                LogUtil.i("当前执行行： " + recordListBean.seq + "  " + recordListBean.id);
                            } else {
                                recordListBean.isCurrent = false;
                                recordListBean.isDrsOpen = false;
                            }
                        }
                        bindData(recordList);
                    }

                    @Override
                    public void onError() {
                        dialog.dismiss();
                    }
                });
            }

            @Override
            public void onError() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void isNotFastClick(View v) {
        switch (v.getId()) {
            case R.id.rlOpen:
                List<RecordListBean> data = mAdapter.getData();
                if (data.size() > 0) {
                    for (RecordListBean b : data) {
                        LogUtil.i("seq" + b.seq);
                    }
                    final LoadingDialog dialog = new LoadingDialog(mActivity);
                    dialog.show();
                    String stepId = data.get(0).id;
                    StaticPresenter.getExRoutingSheetStepByPage(mUserId, mActivity.getBillId(), "up", stepId, Constants.PAGE_SIZE, new CallBack<List<RecordListBean>>() {
                        @Override
                        public void onCompleted(List<RecordListBean> listBeans) {
                            dialog.dismiss();
//                            LogUtil.d("listBeans.size()"+listBeans.size());
                            if (listBeans == null || listBeans.size() < Constants.PAGE_SIZE) {
                                mLlOpen.setVisibility(View.GONE);
//                                ToastUtil.showCenterToast("没有数据了！");
                                List<RecordListBean> beans = mAdapter.getData();
                                assert listBeans != null;
                                beans.addAll(0, listBeans);
                                mAdapter.setNewData(beans);
                            } else {
                                List<RecordListBean> beans = mAdapter.getData();
                                beans.addAll(0, listBeans);
                                mAdapter.setNewData(beans);
                            }
                        }

                        @Override
                        public void onError() {
                            dialog.dismiss();
                        }
                    });
                }
                break;
        }
    }
}
